/*
 * Copyright 2009 rashaguo <rashaguo@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include "webserver.h"
#include "mongoose.h"
#include "utils/logger.h"

static std::string SERVER_PORT = "50000";


class ServerContext
{
public:

    struct mg_context *ctx;
};


WebServerWrapper::WebServerWrapper()
        :m_port(SERVER_PORT), m_isRunning(false)
{
    LOG_DEBUG("init web server wrapper");
    m_context = new ServerContext();
    //m_context->ctx = (struct mg_context*)malloc(sizeof(struct mg_context));
}

WebServerWrapper::~WebServerWrapper()
{
    m_port = "";
    m_isRunning = false;

    delete m_context;
}

int WebServerWrapper::start()
{
    LOG_DEBUG("start web server");
    if((m_context->ctx = mg_start()) == 0)
    {
        m_isRunning = false;
        return -1;
    }
    if( (mg_get_option(m_context->ctx, "ports") == 0) &&
                    (mg_set_option(m_context->ctx, "ports", m_port.c_str()))!= 1)
    {
        m_isRunning = false;
        return -1;
    }

    m_isRunning = true;
    return 0;
}


//To be investigate for the stop
int WebServerWrapper::stop()
{
    LOG_DEBUG("stop web server");
    mg_stop(m_context->ctx);
    m_isRunning = false;
    return 0;
}

int WebServerWrapper::restart()
{
    LOG_DEBUG("restart web server");
    stop();
    start();
    return 0;
}
